<template>
  <div class="app-container">
    <div class="add-manage-container">
      <div class="header">
        <div class="title">
          <el-icon><Plus /></el-icon>
          <span>添加</span>
        </div>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>

      <div class="form-container">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
          <el-form-item label="商户名称" prop="merchantName">
            <el-select v-model="form.merchantName" placeholder="请选择商户名称" clearable filterable style="width: 100%">
              <el-option
                v-for="item in merchantOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-card class="service-table-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>服务项目</span>
                <el-button class="button" type="primary" plain @click="addServiceItem">添加</el-button>
              </div>
            </template>
            
            <el-table 
              :data="serviceItems" 
              style="width: 100%" 
              border
              :row-style="{height: '50px'}"
              :cell-style="{padding: '5px'}"
            >
              <el-table-column label="服务分类" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.categoryName" placeholder="请选择分类" clearable>
                    <el-option
                      v-for="item in categoryOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="服务项目" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.name" placeholder="请输入服务项目" />
                </template>
              </el-table-column>
              <el-table-column label="原价（元）" align="center">
                <template #default="scope">
                  <el-input-number v-model="scope.row.basePrice" :min="0" :precision="2" :step="0.01" />
                </template>
              </el-table-column>
              <el-table-column label="现价（元）" align="center">
                <template #default="scope">
                  <el-input-number v-model="scope.row.nowPrice" :min="0" :precision="2" :step="0.01" />
                </template>
              </el-table-column>
              <el-table-column label="服务介绍" align="left" min-width="200" class-name="description-column">
                <template #default="scope">
                  <div class="description-container">
                    <el-input v-model="scope.row.description" placeholder="请输入服务介绍" type="textarea" :rows="2" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeServiceItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <div class="form-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup name="AddNewManage">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { addManage, listMerchants, listServiceCategories, getServiceNumber } from "@/api/manage/manage"
import { Plus } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const router = useRouter()

// 商户选项
const merchantOptions = ref([])

// 加载商户列表
function loadMerchantOptions() {
  listMerchants().then(response => {
    if (response.code === 200) {
      // 将返回的字符串数组转换为下拉框所需的对象数组格式
      merchantOptions.value = response.rows.map(item => {
        return {
          value: item,
          label: item
        }
      })
    } else {
      proxy.$modal.msgError(response.msg || '获取商户列表失败')
      // 加载失败时使用默认数据
      merchantOptions.value = [
        { value: '兔师傅汽车美容', label: '兔师傅汽车美容' },
        { value: '车享家汽车服务', label: '车享家汽车服务' },
        { value: '车仆汽车服务', label: '车仆汽车服务' }
      ]
    }
  }).catch(err => {
    console.error('获取商户列表出错:', err)
    // 加载失败时使用默认数据
    merchantOptions.value = [
      { value: '兔师傅汽车美容', label: '兔师傅汽车美容' },
      { value: '车享家汽车服务', label: '车享家汽车服务' },
      { value: '车仆汽车服务', label: '车仆汽车服务' }
    ]
  })
}

// 服务分类选项
const categoryOptions = ref([])

// 加载服务类别列表
function loadCategoryOptions() {
  listServiceCategories().then(response => {
    if (response.code === 200) {
      // 将返回的字符串数组转换为下拉框所需的对象数组格式
      categoryOptions.value = response.rows.map(item => {
        return {
          value: item,
          label: item
        }
      })
    } else {
      proxy.$modal.msgError(response.msg || '获取服务类别列表失败')
      // 加载失败时使用默认数据
      categoryOptions.value = [
        { value: '车辆维修', label: '车辆维修' },
        { value: '汽车美容', label: '汽车美容' },
        { value: '汽车保养', label: '汽车保养' }
      ]
    }
  }).catch(err => {
    console.error('获取服务类别列表出错:', err)
    // 加载失败时使用默认数据
    categoryOptions.value = [
      { value: '车辆维修', label: '车辆维修' },
      { value: '汽车美容', label: '汽车美容' },
      { value: '汽车保养', label: '汽车保养' }
    ]
  })
}

// 表单数据
const data = reactive({
  form: {
    merchantName: '',
    serviceItems: []
  },
  rules: {
    merchantName: [
      { required: true, message: '请选择商户名称', trigger: 'change' }
    ]
  }
})

const { form, rules } = toRefs(data)
const serviceItems = ref([])
const formRef = ref(null)

// 添加服务项
async function addServiceItem() {
  try {
    // 调用后端接口获取服务编号
    const response = await getServiceNumber();
    console.log('获取服务编号响应:', response); // 添加调试信息
    
    let serviceNo = '';
    
    // 处理返回的服务编号 - 适配多种可能的返回格式
    if (response) {
      if (response.code === 200 && response.data) {
        // 标准格式 {"code":200,"msg":"操作成功","data":"17522060334240002"}
        serviceNo = response.data;
        console.log('使用后端生成的服务编号(data):', serviceNo);
      } else if (response.code === 200 && response.msg && !isNaN(response.msg)) {
        // 另一种格式 {"msg":"17522060334240002","code":200}
        serviceNo = response.msg;
        console.log('使用后端生成的服务编号(msg):', serviceNo);
      } else if (typeof response === 'string' && !isNaN(response)) {
        // 直接返回字符串数字
        serviceNo = response;
        console.log('使用后端生成的服务编号(string):', serviceNo);
      } else {
        // 无法识别的格式，使用备用方案
        serviceNo = 'S' + Date.now().toString();
        console.warn('无法识别的响应格式，使用备用编号:', serviceNo, '响应内容:', response);
      }
    } else {
      // 响应为空，使用备用方案
      serviceNo = 'S' + Date.now().toString();
      console.warn('响应为空，使用备用编号:', serviceNo);
    }

    // 添加新的服务项
    serviceItems.value.push({
      serviceNo: serviceNo,
      categoryName: '',
      name: '',
      basePrice: 0,
      nowPrice: 0,
      description: ''
    });
  } catch (error) {
    console.error('获取服务编号失败:', error);
    // 出错时使用备用方案
    const backupServiceNo = 'S' + Date.now().toString().slice(-8) + Math.floor(Math.random() * 1000);
    serviceItems.value.push({
      serviceNo: backupServiceNo,
      categoryName: '',
      name: '',
      basePrice: 0,
      nowPrice: 0,
      description: ''
    });
    proxy.$modal.msgWarning('获取服务编号失败，使用临时编号');
  }
}

// 移除服务项
function removeServiceItem(index) {
  serviceItems.value.splice(index, 1)
}

// 不再需要前端生成服务编号的方法
// function generateServiceNo() {
//   return 'S' + Date.now().toString().slice(-8) + Math.floor(Math.random() * 1000)
// }

// 取消按钮
function cancel() {
  router.back()
}

// 提交表单
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (serviceItems.value.length === 0) {
        proxy.$modal.msgError('请至少添加一个服务项目')
        return
      }

      // 验证服务项
      let isValid = true
      serviceItems.value.forEach((item, index) => {
        if (!item.categoryName) {
          proxy.$modal.msgError(`第${index + 1}行的服务分类不能为空`)
          isValid = false
        }
        if (!item.name) {
          proxy.$modal.msgError(`第${index + 1}行的服务项目不能为空`)
          isValid = false
        }
      })

      if (!isValid) return

      // 构建提交数据
      const submitData = serviceItems.value.map(item => {
        return {
          serviceNo: item.serviceNo,
          name: item.name,
          categoryName: item.categoryName,
          merchantName: form.value.merchantName,
          description: item.description,
          basePrice: item.basePrice,
          nowPrice: item.nowPrice
        }
      })

      // 提交到后端
      const loading = proxy.$loading({
        lock: true,
        text: '提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // 使用Promise.all批量提交多个服务项
      const addPromises = submitData.map(item => addManage(item))
      
      Promise.all(addPromises)
        .then(responses => {
          proxy.$modal.msgSuccess('添加成功')
          router.push('/merchant/manage')
        })
        .catch(error => {
          console.error('添加失败:', error)
          proxy.$modal.msgError('添加失败: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          loading.close()
        })
    }
  })
}

// 页面挂载时加载数据
onMounted(() => {
  // 加载商户和服务类别数据
  loadMerchantOptions()
  loadCategoryOptions()
  
  // 初始化添加一个空行
  addServiceItem()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.add-manage-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.title .el-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #409eff;
}

.form-container {
  padding: 10px;
}

.service-table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.form-footer .el-button {
  min-width: 120px;
}

.el-table :deep(.el-input),
.el-table :deep(.el-select),
.el-table :deep(.el-input-number) {
  width: 100%;
}

.el-table :deep(.el-input-number .el-input__wrapper) {
  box-shadow: none;
}

.el-table :deep(.el-input__wrapper),
.el-table :deep(.el-select__wrapper) {
  box-shadow: none;
}

/* 设置表格行高 */
.el-table :deep(.el-table__row) {
  height: 50px;
}

/* 设置表格单元格内容垂直居中 */
.el-table :deep(.el-table__cell) {
  padding: 8px 0;
}

/* 确保输入框在单元格中垂直居中 */
.el-table :deep(.el-input__wrapper),
.el-table :deep(.el-select__wrapper),
.el-table :deep(.el-input-number) {
  height: 32px;
  line-height: 32px;
}

/* 设置描述列的样式 */
.el-table :deep(.description-column) {
  text-align: left;
}

.description-container {
  max-width: 100%;
  overflow-x: auto;
}

.description-container :deep(.el-textarea__inner) {
  min-height: 60px;
}

/* 设置水平滚动条样式 */
.description-container::-webkit-scrollbar {
  height: 6px;
}

.description-container::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.description-container::-webkit-scrollbar-track {
  background-color: #f0f2f5;
}
</style> 